// pages/applicationsList/applicationsList.js
let applicantSum = -1;//获取一共申请人总数，用于结束下拉获取数据
const db = wx.cloud.database().collection("applicant");
Page({
  data: {
    recruit_name:"...",
    recruit_id:'',
    sum:35,//招募的总限制人数
    passNum:0,
    inputNum:-1,
    selectAll:false,
    showMask: false,
    showChangeDialog:false,
    showAdmitDialog:false,
    showRefuseDialog:false,
    applicantList:[]
    },
	
    //单选
    select:function(e){
     let flag = 1;
     let index = e.currentTarget.dataset.index;
     let applicantList = this.data.applicantList;
     let newLi = 'applicantList[' + index + '].checked';
     this.setData({
       [newLi]:!this.data.applicantList[index].checked
     })
     //进行全选判断
     for(let i=0; i<applicantList.length && flag; i++){
       if(applicantList[i].checked==false){
         flag = 0;
         break;
       }
     }
     if(flag==1){
      this.setData({
        selectAll:true
      })
     }else{
      this.setData({
        selectAll:false
      })
     }
    },
    //全选和取消全选
    checkAll: function(e){
      console.log("点击了");
      let that = this;
      let list = this.data.applicantList;
      let selectAll = this.data.selectAll;
      if(selectAll==false){
        list.forEach(item=>{
          item.checked=true;
        })
        that.setData({
          applicantList:list,
          selectAll:true
        })
      }else{
        list.forEach(item=>{
          item.checked=false;
        })
        that.setData({
            applicantList:list,
            selectAll:false
        })
      }
    },

    //修改人数弹窗代码
    changeNumDialog:function(e){
      this.setData({
        showMask:true,
        showChangeDialog:true
      })
    },
    //判断是否有选择申请人
    isCheckOne:function(e){
      let applicantList = this.data.applicantList;
      for(let i=0; i<applicantList.length; i++){
        if(applicantList[i].checked==true){
          return true;
        }
      }
      return false;
    },
    
    //计算修改通过人数
    changePassNum:function(e){
      let applicantList = this.data.applicantList;
      let count = 0;
      for(let i=0; i<applicantList.length; i++){
        if(applicantList[i].applicationStatus==1){
         count++;
        }
      }
      this.setData({
        passNum:count
      })
      
    },
    //取消所有的选择项
    cancelAll:function(e){
      let applicantList = this.data.applicantList;
      applicantList.forEach(item=>{
        item.checked = false;
      })
      this.setData({
        applicantList,
        selectAll:false
      }) 
    },
    //审核通过弹窗代码
    admitDialog:function(e){
      if(this.isCheckOne()){
        this.setData({
          showMask:true,
          showAdmitDialog:true
        })	  
      }else{
        wx.showModal({
          title: '友情提示',
          content: '请选择一名申请人'
        })
      }
    },
    //审核拒绝通过弹窗代码
    refuseDialog:function(e){
      if(this.isCheckOne()){
        this.setData({
        showMask:true,
        showRefuseDialog:true
        })
      }else{
        wx.showModal({
          title: '友情提示',
          content: '请选择一名申请人'
        })
      }
    },
    //三个弹窗退出时的函数,有冗余，但是懒得写三个函数了
    quitDialog:function(e){
      this.setData({
      showMask: false,
      showChangeDialog:false,
      showAdmitDialog:false,
      showRefuseDialog:false
      })
    },
    //获取input的值便于向父组件传参
    handleInput:function(e){
      this.setData({
        inputNum:Number(e.detail.value)
      })
    },
    //确定修改人数的按钮的函数
    changeNum:function(e){
      let sum;
      if(this.data.inputNum == -1){//当使用默认显示的值时，inputNum没有改变，所以使用回原来的sum值
		this.setData({
		    showMask: false,
		    showChangeDialog:false,
		})
      }else if(this.data.inputNum >= this.data.passNum){
        sum = this.data.inputNum;
        console.log('人数',this.data.sum)
        console.log('id',this.data.recruit_id)
        wx.cloud.callFunction({
          name:'recruit',
          data:{
            parameter:'updateRecruitNumberById',
            recruitNumber:sum,
            id:this.data.recruit_id
          }
        }).then(res=>{
          console.log(res)
        }).catch(err=>{
          console.log(err)
        })
        this.setData({
            showMask: false,
            showChangeDialog:false,
            sum
        })
      }else if(this.data.inputNum < this.data.passNum){
        wx.showModal({
          title: '友情提示',
          content: '修改的人数不能少于通过的人数噢！'
        })
	  }
      
      
    },
	//使用云函数修改申请人状态
	changeStatus:function(status,id){
		wx.cloud.callFunction({
			name:'applicant',
			data:{
			parameter:'updateApplicationStatusById',
			status:status,
			id:id
		}
		}).then(res=>{
		  console.log(res)
		}).catch(err=>{
		  console.log(err)
		})
	},
	//发送邮件的函数，flag为0为通过，flag为1则为拒绝
  sendEmail:function(userId,name,recruitName,flag){//传过来的用户id和名字
    // console.log('recruitName',recruitName)
		let result;
		let mg;
		if(flag == 0){
			result = '录取';
			mg = '恭喜你已经被录取';
		}else if(flag){
			result = '未录取';
			mg = '你没有被我们录取。';
		}
		wx.cloud.callFunction({
		  name:'messagePush',
		  data:{
			userId:userId,
			result:result,
			userName:'尊敬的'+name,
			mg:mg,
			recruitName:this.data.recruit_name,
			// reviewer:applicant.recruit.personLiable,           //  
			tips:'无',
			// admissionTime:time.formatTimeTwo(Date.parse(new Date())/1000,'Y.M.D'),
		  }
		}).then(res=>{
		  console.log('成功',res)
		}).catch(err=>{
		  console.log('失败',err)
		})
	},

    //审核通过点击确定的函数
    passChecked:function(e){
      let that = this;
      let applicantList = this.data.applicantList;
      let count = 0;//记录点击审核通过后会变成通过的总人数
	  applicantList.forEach(item=>{
		  if(item.checked == true || item.applicationStatus == 1){
			  count++
		  }
	  })
	  if(count <= this.data.sum){
		  for(let i=0;i<applicantList.length;i++){
		    if(applicantList[i].checked===true){
		      if(applicantList[i].applicationStatus==1){
		        //通过的不发邮件，不处理
          }else if(applicantList[i].applicationStatus==0){//审核中的代码部分
            console.log("userId:" + applicantList[i].userId + "，userName:" + applicantList[i].name + "recruit._id:" + applicantList[i].recruit._id);
            this.sendEmail(applicantList[i].userId,applicantList[i].name,applicantList[i].recruit._id,0);//发送邮件  
            applicantList[i].applicationStatus=1;
            this.changeStatus(1,applicantList[i]._id);
		      }else if(applicantList[i].applicationStatus==2){//未通过的代码部分
            this.sendEmail(applicantList[i].userId,applicantList[i].name,applicantList[i].recruit._id,0);//发送邮件
            console.log("userId:" + applicantList[i].userId + "，userName:" + applicantList[i].name + "，recruit._id:" + applicantList[i].recruit._id);
            applicantList[i].applicationStatus=1;
            this.changeStatus(1,applicantList[i]._id);
		      }
		    }
		  }
		  this.setData({
		    applicantList
		  })
		  this.quitDialog();
		  this.changePassNum();
		  this.cancelAll();
	  }else{
		  this.quitDialog();
		  this.cancelAll();
		  wx.showModal({
		    title: '友情提示',
		    content: '审核通过人数超出总人数限制！'
		  })
	  }
    },
    //审核拒绝点击确定的函数
    refuseChecked:function(e){
      let that = this;
      let applicantList = this.data.applicantList;
      for(let i=0;i<applicantList.length;i++){
        if(applicantList[i].checked===true){
          if(applicantList[i].applicationStatus==2){
            //未通过的不发邮件，不处理
            
          }else if(applicantList[i].applicationStatus==0){//审核中的代码部分
            this.sendEmail(applicantList[i].userId,applicantList[i].name,applicantList[i].recruit._id,1);//发送邮件
			      console.log("拒绝++++：userId:" + applicantList[i].userId + "，userName:" + applicantList[i].name + "，recruit._id:" + applicantList[i].recruit._id);
            applicantList[i].applicationStatus=2;
            this.changeStatus(2,applicantList[i]._id);
            
          }else{//通过的代码部分
            this.sendEmail(applicantList[i].userId,applicantList[i].name,applicantList[i].recruit._id,1);//发送邮件
			      console.log("通过-----：userId:" + applicantList[i].userId + "，userName:" + applicantList[i].name + "，recruit._id:" + applicantList[i].recruit._id);
            applicantList[i].applicationStatus=2;
			      this.changeStatus(2,applicantList[i]._id);
          }
        }
      }
      this.setData({
        applicantList
      })
      this.quitDialog();
      this.changePassNum();
      this.cancelAll();
    },
    //跳转到详细页面，简单实现了跳转，传了被点击的人的下标，具体要传递什么参数后面再补充代码
    turnToDetail:function(e){
      // let id = e.currentTarget.dataset.id; //传递id
      let applicant = e.currentTarget.dataset.applicant   //传递对象
      let applicantStr = JSON.stringify(applicant)
      // console.log("点击了下标为"+applicant+"的申请人")
      wx.navigateTo({
        // url: '/pages/applicationDetails/applicationDetails?id='+id,
        url: '/pages/applicationDetails/applicationDetails?applicant='+applicantStr
      })
    },
	//封装获取申请人数，一次12条
	getApplicants:function(e){
		if(applicantSum == this.data.applicantList.length){
			wx.showToast({
				 title:"已加载全部"
			})
			return; 
		}
		wx.showLoading({
			title:"加载中"
		})
		let length = this.data.applicantList.length;
		console.log("长度为："+length)
		db.where({
				 recruitId:e
    }).orderBy('createTime','desc') //根据创建时间降序排序
    .skip(length).limit(12).get().then(res=>{ 
			//在获取到申请人数组后给每个申请人添加一个checked变量，用于全选和取消全选功能
			console.log('12条数据',res)
			let list = res.data;
			let count = 0;
			list.forEach(item=>{
				item.checked = false;
				if(item.applicationStatus==1){//计算通过人数
				  count++;
				}
				console.log("设置了checked为false")
			})
			this.setData({
				applicantList:this.data.applicantList.concat(list),
				passNum:this.data.passNum + count,
				selectAll:false
			})
		  wx.hideLoading()
		}).catch(err=>{
		  console.log(err)
		  wx.showToast({
			  title:"加载失败"
		  })
		})
  },
  // 下拉刷新  内容
  myPullDownRefresh:function(){
      //在当前页面显示导航条加载动画
      wx.showNavigationBarLoading(); 
      //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
      wx.showLoading({
        title: '刷新中...',
      })
      this.getApplicants(this.data.recruit_id);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     const id = options.id
    // 利用缓存加载，招募信息 
    const myRecruitAll=wx.getStorageSync('recruitAll')
    for (let index = 0; index < myRecruitAll.length; index++) {
      if(myRecruitAll[index]._id==id){
        this.setData({
          recruit_name:myRecruitAll[index].recruitName,
          sum:myRecruitAll[index].recruitNumber,
          recruit_id: myRecruitAll[index]._id
        })
        console.log('匹配申请列表招募信息成功')
        break
      }
    }
    // 获取总申请数，用于结束下拉加载
    wx.cloud.callFunction({
      name:'getApplicantSum',
      data:{
        recruitId:id
      }
    }).then(res=>{
      applicantSum = res.result.total;
      console.log("总数获取成功:"+applicantSum)
    }).catch(err=>{ 
      console.log(err)
    })
	  this.getApplicants(id);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.myPullDownRefresh()
    wx.hideLoading();
    //隐藏导航条加载动画
    wx.hideNavigationBarLoading();
    //停止下拉刷新
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
	this.getApplicants(this.data.recruit_id);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})